<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="mode==='add'?'新增成员':'编辑成员'"
    :close-on-click-modal="false"
    width="750px"
    @close="close"
  >
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="110px" size="small">
      <el-form-item label="所属组织：" prop="orgIds">
        <el-cascader
          v-model="form.orgIds"
          :props="{expandTrigger: 'hover',label:'name',value:'id', checkStrictly: true }"
          placeholder="请选择"
          :options="parentOptions"
        />
      </el-form-item>
      <el-form-item label="成员姓名：" prop="name">
        <el-input v-model="form.name" maxlength="15" show-word-limit placeholder="请输入" />
      </el-form-item>
      <el-form-item label="手机号：" prop="mobilePhone">
        <el-input v-model="form.mobilePhone" placeholder="请输入" :maxlength="11" show-word-limit />
      </el-form-item>
      <el-form-item label="登录账号：" prop="username">
        <el-input v-model="form.username" maxlength="12" show-word-limit placeholder="请输入" />
      </el-form-item>
      <el-form-item v-if="mode === 'add'" label="登录密码：" prop="initPassword">
        <el-input type="password" style="display:none" />
        <el-input
          v-model="form.initPassword"
          type="password"
          maxlength="12"
          show-word-limit
          placeholder="请输入"
          autocomplete="new-password"
        />
      </el-form-item>
      <el-form-item label="选择角色：" prop="roles">
        <el-select v-model="form.roles" value-key="id" multiple placeholder="请选择" filterable>
          <el-option v-for="item in rolesOptions" :key="item.id" :label="item.name" :value="item" />
        </el-select>
      </el-form-item>

      <el-form-item label="备注：" prop="description">
        <el-input v-model="form.description" maxlength="30" placeholder="备注" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" :disabled="loading" round @click="hide">取 消</el-button>
      <el-button size="small" :disabled="loading" round type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addUser, updateUser } from '@/api/user/index'
import { roleList } from '@/api/user/role'
import { menusTreeToList, findTreeParent } from '@/utils/menus'
import { validEngNum, validMobilePhone } from '@/utils/validate'

export default {
  data() {
    // 校验方法
    // 登录名
    const validateUserName = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback(new Error('请输入登录名'))
      } else if (!validEngNum(value, 6, 12)) {
        callback(new Error('长度为6~12个字符,支持数字,大小写字母'))
      } else {
        callback()
      }
    }
    // 密码
    const validateInitPassword = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback(new Error('请输入密码'))
      } else if (!validEngNum(value, 6, 12)) {
        callback(new Error('长度为6~12个字符,支持数字,大小写字母'))
      } else {
        callback()
      }
    }
    // 手机号
    const validateMobilePhone = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback(new Error('请输入手机号码'))
      } else if (!validMobilePhone(value)) {
        callback(new Error('请输入11位手机号'))
      } else {
        callback()
      }
    }
    return {
      // 校验字段
      rules: {
        orgIds: [
          {
            required: true,
            type: 'array',
            message: '请选择组织架构',
            trigger: ['change']
          }
        ],
        name: [
          {
            required: true,
            message: '请输入成员名',
            trigger: ['blur', 'change']
          }
        ],
        initPassword: [
          {
            required: true,
            validator: validateInitPassword,
            trigger: ['blur', 'change']
          }
        ],
        mobilePhone: [
          {
            required: true,
            validator: validateMobilePhone,
            trigger: ['blur', 'change']
          }
        ],
        username: [
          {
            required: true,
            validator: validateUserName,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      title: null,
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      mode: 'add',
      parentOptions: [],
      rolesOptions: [],
      parentId: null,
      form: {
        avatar: null,
        description: null,
        initPassword: null,
        isAdmin: false,
        mobilePhone: null,
        name: null,
        username: null,
        orgIds: [],
        roles: [],
        status: 1
      }
    }
  },
  computed: {},
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {

  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    // 弹框相关
    open({ mode = 'add', parentId = -1, treeList = [], row = null }) {
      this.mode = mode
      this.parentOptions = treeList
      if (row) {
        this.parentId = row.orgList && row.orgList.length && row.orgList[row.orgList.length - 1].orgId || -1
        this.form = Object.assign({}, row)
      } else {
        this.parentId = parentId
      }
      this.getRoleOptions()
      this.findParentIds()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    close() {
      this.parentId = null
      this.form = {
        avatar: null,
        description: null,
        initPassword: null,
        isAdmin: false,
        mobilePhone: null,
        name: null,
        username: null,
        orgIds: [],
        roles: [],
        status: 0
      }
      this.$refs.form.resetFields()
      this.loading = false
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const params = Object.assign({}, this.form)
          params.orgIds = params.orgIds.length && [params.orgIds[params.orgIds.length - 1]] || []
          const apiFun = this.mode === 'add' ? addUser : updateUser
          apiFun({ data: params }).then(() => {
            this.$notify({
              title: '成功',
              message: this.mode === 'add' ? '新增成功' : '更新成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.resolve && this.resolve()
            this.hide()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },

    /**
     * 数据组
     */
    // 获取角色
    getRoleOptions() {
      this.loading = true
      roleList().then(res => {
        this.rolesOptions = res.data || []
      }).finally(() => {
        this.loading = false
      })
    },

    // 找父节点
    findParentIds() {
      if (this.parentId && this.parentId !== -1) {
        const parentList = menusTreeToList(this.parentOptions)
        const currentList = findTreeParent(parentList, this.parentId)
        const parentIds = []
        for (let i = 0; i < currentList.length; i++) {
          parentIds.push(currentList[i].id)
        }
        this.form.orgIds = parentIds
      } else {
        this.form.orgIds = []
      }
    }
    /**
     * 按钮组
     */

    /**
     * 状态组
     */

    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/*reset*/
.el-cascader,.el-select {
  width: 100%;
}
</style>
